package cn.iocoder.yudao.module.picturebook.utils;

import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 自定义 MultipartFile 实现类（不依赖 spring-test）
 */
public class CustomMultipartFile implements MultipartFile {

    private final File file;
    private final String name;
    private final String originalFilename;
    private final String contentType;

    public CustomMultipartFile(File file) {
        this.file = file;
        this.name = "file"; // 参数名，与 OSS 工具类要求一致
        this.originalFilename = file.getName();
        this.contentType = getContentType(file.getName()); // 自动识别 MIME 类型
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getOriginalFilename() {
        return originalFilename;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return file.length() == 0;
    }

    @Override
    public long getSize() {
        return file.length();
    }

    @Override
    public byte[] getBytes() throws IOException {
        try (FileInputStream fis = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
            return bos.toByteArray();
        }
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new FileInputStream(file); // 返回文件输入流
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        // 可选实现：将文件转存到目标路径
        java.nio.file.Files.copy(file.toPath(), dest.toPath());
    }

    // 简单判断文件 MIME 类型
    private String getContentType(String fileName) {
        if (fileName.endsWith(".mp3")) {
            return "audio/mpeg";
        } else if (fileName.endsWith(".png")) {
            return "image/png";
        } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
            return "image/jpeg";
        } else {
            return "application/octet-stream";
        }
    }
}